package main

import (
	"fmt"
	"os"
	"strings"
)

// 删除环境
func handleDelete(args []string) {
	if len(args) == 0 {
		fmt.Println("请指定环境名称")
		fmt.Println("用法: genv delete <环境名>")
		os.Exit(1)
	}

	targetEnv := args[0]
	output, err := runGit("stash", "list")
	if err != nil {
		fmt.Printf("环境查询失败: %v\n", err)
		return
	}

	var toDelete []string
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		parts := strings.SplitN(line, ": ", 3)
		if len(parts) >= 3 && parts[2] == targetEnv {
			indexPart := strings.Split(parts[0], " ")[0]
			index := strings.TrimPrefix(indexPart, "stash@{")
			index = strings.TrimSuffix(index, "}")
			toDelete = append(toDelete, index)
		}
	}

	if len(toDelete) == 0 {
		fmt.Printf("未找到环境: %s\n", targetEnv)
		return
	}

	for i := len(toDelete) - 1; i >= 0; i-- {
		_, err := runGit("stash", "drop", fmt.Sprintf("stash@{%s}", toDelete[i]))
		if err != nil {
			fmt.Printf("删除失败: %v\n", err)
			return
		}
	}
	fmt.Printf("已删除环境: %s (共 %d 个配置)\n", targetEnv, len(toDelete))
}
